package controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;

import po.Client;
import po.Dish;
import po.Merchant;
import po.OrderItems;
import po.Orders;
import service.MerchantService;
import service.OrdersService;
import util.Po2Vo;
import vo.OrdersVo;

@Controller
public class GradeController {
	
	@Autowired
	private OrdersService ordersService;
	@Autowired
	private MerchantService merchantService;
	
	@RequestMapping(value = "grade", method = {RequestMethod.POST})
	public String orderGrade(int grade, String oid, HttpSession session) {
		System.out.println(grade);
		Orders orders = ordersService.findOrder(oid);
		orders.setOgrade(grade);
		String mString = ordersService.updateOrdersGrade(orders);
		
		Orders orders2 = ordersService.findOrder(orders.getoId());
		session.setAttribute("orders", orders2);
		return "redirect:/merchantGrade";
	}
	
	@RequestMapping(value = "merchantGrade")
	public String merchantGrade(HttpSession session) throws JsonProcessingException {
		Orders orders = (Orders) session.getAttribute("orders");
		Merchant merchant = ordersService.calculateNewMerchantGrade(orders);
		String mString = merchantService.updateMerchantGrade(merchant);
		Merchant merchant2 = merchantService.getMerchant(merchant.getmId());
		return orders.getoId();
	}
	
	@RequestMapping(value = "gradeFromHistory", method = {RequestMethod.POST})
	public String orderGradeFromHistory(int grade, String oid, HttpSession session) {
		System.out.println(grade + "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
		Orders orders = ordersService.findOrder(oid);
		orders.setOgrade(grade);
		String mString = ordersService.updateOrdersGrade(orders);
		Orders orders2 = ordersService.findOrder(orders.getoId());
		session.setAttribute("orders", orders2);
		return "redirect:/merchantGradeFromHistory";
	}
	
	@RequestMapping(value = "merchantGradeFromHistory")
	@ResponseBody
	public OrdersVo merchantGradeFromHistory(HttpSession session) throws JsonProcessingException {
		Orders orders = (Orders) session.getAttribute("orders");
		Merchant merchant = ordersService.calculateNewMerchantGrade(orders);
		String mString = merchantService.updateMerchantGrade(merchant);
		Merchant merchant2 = merchantService.getMerchant(merchant.getmId());
		
		OrdersVo ordersVo = ordersService.findOrderVo(orders.getoId());
		return ordersVo;
	}
}
